package dailytest;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @Author: youdao.hww
 * @Date: 7/20/24
 * @Desc:
 */
public class StackTraceExample {

    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        String str;
        try {
            throwable.printStackTrace(pw);
            str = sw.toString();
        } finally {
            pw.close();
        }
        return str;
    }

    public static void main(String[] args) throws InterruptedException {
        //计数器
        CountDownLatch countDownLatch = new CountDownLatch(100);
        ExecutorService threadPoolTaskExecutor = Executors.newFixedThreadPool(2);
        System.out.println("main start ");

        for (int i = 0; i < 100; i++) {
            int finalI = i;
            threadPoolTaskExecutor.execute(() -> {
                try {
                    testThread(finalI);
                } catch (Exception e) {
                    System.out.println(Thread.currentThread().getId() + "出现异常: ");
                    e.printStackTrace();
                    System.out.println("----------------------");
                    System.out.println(getStackTrace(e));
                } finally {
                    //扣减计数器
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        threadPoolTaskExecutor.shutdown();
        System.out.println("main end  ");
    }

    private static void testThread(int i) {
        if (i == 3) {
            int result = 1 / 0;
        }
        System.out.println(Thread.currentThread().getId() + "正常执行");
    }
}
